﻿using QD.Tools;
using QD_Clients.Code;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Validation;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD_Clients
{
    public partial class SysManager : BaseForm
    {
        string _strState = "";
        private PageState PageState = PageState.Browse;
        private Control[] readIgnoreControls;
        public SysManager()
        {
            InitializeComponent();

            #region 注册菜单
            base.ToolsBtnAdd = this.toolStripButton4;
            base.ToolsBtnModify = this.toolStripButton7;
            base.ToolsBtnUpdate = this.toolStripButton5;
            base.ToolsBtnDelete = this.toolStripButton3;
            base.ToolsBtnDetail = this.toolStripButton8;
            base.ToolsBtnClose = this.toolStripButton2;
            base.ToolsBtnPrevious = this.ts_prev;
            base.ToolsBtnNext = this.ts_next;
            #endregion

            this.grid_list.InitGrid();
            this.grid_list.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;
        }

        private void SysManager_Load(object sender, EventArgs e)
        {
            readIgnoreControls = new Control[] { this.Uid, this.CreateDate };
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, readIgnoreControls);

            this.label5.Text = "修改用户时如果输入密码，则会修改用户密码！";
        }
        public override void ToolsBtnAdd_Click(object sender, EventArgs e)
        {
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, readIgnoreControls);

            this.tabControl1.SelectedIndex = 0;
            PageState = PageState.Append;
            this.Uid.Text = "";
            this.UName.Text = "";
            this.CreateDate.Text = "";
            this.Pwd.Text = "";
            this.PwdAgain.Text = "";
            this.IsForbidLogon.Checked = false;
        }

        protected override void ToolsBtnDelete_Click(object sender, EventArgs e)
        {
            //PromptHelper.Prompt("暂不支持删除用户！");
            DialogResult isOk = PromptHelper.PromptOkCancel("确定删除吗？");
            if (isOk == DialogResult.OK)
            {
                try
                {
                    var uid = this.Uid.Text;
                    if (!string.IsNullOrEmpty(uid))
                    {
                        QDDevPlat_V4 db = new QDDevPlat_V4();

                        string sql = @"delete from Sys_Manager where Uid='" + uid + "';";
                        db.ExecuteScalar(sql);
                        this.Uid.Text = "";
                        this.UName.Text = "";
                        this.CreateDate.Text = "";
                        this.Pwd.Text = "";
                        this.PwdAgain.Text = "";
                        this.IsForbidLogon.Checked = false;
                        GridList_DataBind();
                        PromptHelper.Prompt("删除成功！");
                    }
                    else
                    {
                        PromptHelper.Prompt("请选择用户！");
                    }
                }
                catch (Exception ex)
                {
                    PromptHelper.Prompt(ex);
                }

            }
        }

        protected override void ToolsBtnDetail_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid_list.SelectedCells;
            if (cells.Count == 0)
            {
                PromptHelper.Prompt("请选择要查看的用户！");
            }
            else
            {
                string uid = this.grid_list.Rows[cells[0].RowIndex].Cells["ListUid"].Value.ToString();
                InitUIData(uid);
            }
        }

        protected override void ToolsBtnModify_Click(object sender, EventArgs e)
        {
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, readIgnoreControls);
            PageState = PageState.Modify;

            this.Uid.ReadOnly = true;
        }

        protected override void ToolsBtnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState == PageState.Append || PageState == PageState.Modify)
                {
                    string uid = this.Uid.Text.Trim();
                    string uname = this.UName.Text.Trim();

                    using (QDDevPlat_V4 db = new QDDevPlat_V4())
                    {
                        #region 保存表单主表
                        Sys_Manager mod = null;
                        if (PageState == PageState.Append)
                        {
                            mod = new Sys_Manager();
                            if (db.Sys_Manager.Any(p => p.Uid == uid))
                            {
                                throw new Exception("用户编号已经存在！");
                            }
                            else if (db.Sys_Manager.Any(p => p.UserName == uname))
                            {
                                throw new Exception("用户姓名已经存在！");
                            }
                            else
                            {
                                string _pwd = this.Pwd.Text.Trim();
                                string _pwdAgain = this.PwdAgain.Text.Trim();
                                if (string.IsNullOrEmpty(_pwd))
                                {
                                    throw new Exception("请输入密码！");
                                }
                                else if (string.IsNullOrEmpty(_pwdAgain))
                                {
                                    throw new Exception("请确认密码！");
                                }
                                else if (_pwd != _pwdAgain)
                                {
                                    throw new Exception("两次输入密码不一致！");
                                }
                                else
                                {
                                    mod.Uid = uid;
                                    mod.Pwd = _pwd.ToMD5Encryption();
                                    mod.CreateDate = DateTime.Now;
                                    db.Sys_Manager.Add(mod);
                                }
                            }
                            mod.CreateDate = DateTime.Now;
                        }
                        else
                        {
                            if (!db.Sys_Manager.Any(p => p.Uid == uid))
                            {
                                throw new Exception("用户" + uid + "不存在或已经被删除，操作失败！");
                            }
                            else
                            {
                                mod = db.Sys_Manager.FirstOrDefault(p => p.Uid == uid);
                                string pwd = this.Pwd.Text;
                                string pwdAgain = this.PwdAgain.Text;
                                if (!string.IsNullOrEmpty(pwd) || !string.IsNullOrEmpty(pwdAgain))
                                {
                                    if (pwd != pwdAgain)
                                    {
                                        throw new Exception("两次输入密码不一致！");
                                    }
                                    else
                                    {
                                        mod.Pwd = pwd.ToMD5Encryption();
                                    }
                                }
                            }
                        }

                        mod.UserName = uname;
                        mod.ForbidLogon = this.IsForbidLogon.Checked;

                        if (string.IsNullOrEmpty(mod.Uid))
                        {
                            throw new Exception("用户编号不能为空！");
                        }
                        else if (string.IsNullOrEmpty(mod.UserName))
                        {
                            throw new Exception("用户姓名不能为空！");
                        }
                        #endregion

                        db.SaveChanges();
                    }
                    PromptHelper.Prompt("保存成功！");

                    ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, readIgnoreControls);
                    PageState = PageState.Browse;

                    GridList_DataBind();
                    InitUIData(uid);
                }
            }
            catch (DbEntityValidationException ex)
            {
                GeneralTools.EFValidaPrompt(ex);
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            GridList_DataBind();
            this.tabControl1.SelectedIndex = 1;
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        private void GridList_DataBind()
        {
            QDDevPlat_V4 db = new QDDevPlat_V4();
            string key = this.txtKey.Text.Trim().ToLower();
            string sql = string.Format("select * from Sys_Manager");
            string strWhere = " where 1=1 ";

            string _key = this.txtKey.Text.Trim();
            if (!string.IsNullOrEmpty(_key))
            {
                strWhere += string.Format(" and (Uid like '%{0}%' or UserName like '%{0}%')", _key);
            }
            if (!string.IsNullOrEmpty(_strState))
            {
                strWhere += string.Format(" and (ForbidLogon = '{0}')", _strState);
            }
            DataTable dt = db.Query(sql + strWhere);

            this.grid_list.DataSource = dt;
        }

        private void grid_list_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                string uid = this.grid_list.Rows[e.RowIndex].Cells["ListUid"].Value.ToString();
                InitUIData(uid);
            }
        }

        protected override void InitUIData(string uid)
        {
            bool isInit = true;

            if (PageState != PageState.Browse && PromptHelper.PromptOkCancel("当前数据未保存，是否放弃保存？") == DialogResult.Cancel)
            {
                isInit = false;
            }
            if (isInit)
            {
                QDDevPlat_V4 db = new QDDevPlat_V4();
                Sys_Manager mod = db.Sys_Manager.First(p => p.Uid == uid);

                this.Uid.Text = mod.Uid;
                this.UName.Text = mod.UserName;
                this.IsForbidLogon.Checked = mod.ForbidLogon;
                this.CreateDate.Text = mod.CreateDate.ToString();
                this.Pwd.Text = "";
                this.PwdAgain.Text = "";
                this.Uid.ReadOnly = true;
                this.tabControl1.SelectedIndex = 0;

                PageState = PageState.Browse;
                ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, readIgnoreControls);
            }
            base.InitUIData(uid);
        }

        private void Sys_ManagerMag_Shown(object sender, EventArgs e)
        {
            this.txtKey.Focus();
        }

        protected override void ToolsBtnPrevious_Click(object sender, EventArgs e)
        {
            Sys_Manager ftMod = IsCurrentExists();
            if (ftMod != null)
            {
                QDDevPlat_V4 dbConfig = new QDDevPlat_V4();
                Sys_Manager mod = dbConfig.Sys_Manager.Where(p => p.CreateDate < ftMod.CreateDate).OrderByDescending(p => p.CreateDate).FirstOrDefault();
                if (mod == null)
                {
                    PromptHelper.Prompt("已经是第一条数据了！");
                }
                else
                {
                    InitUIData(mod.Uid);
                }
            }
        }

        protected override void ToolsBtnNext_Click(object sender, EventArgs e)
        {
            Sys_Manager ftMod = IsCurrentExists();
            if (ftMod != null)
            {
                QDDevPlat_V4 dbConfig = new QDDevPlat_V4();
                Sys_Manager mod = dbConfig.Sys_Manager.Where(p => p.CreateDate > ftMod.CreateDate).OrderBy(p => p.CreateDate).FirstOrDefault();
                if (mod == null)
                {
                    PromptHelper.Prompt("已经是最后一条数据了！");
                }
                else
                {
                    InitUIData(mod.Uid);
                }
            }
        }

        private Sys_Manager IsCurrentExists()
        {
            Sys_Manager ftMod = null;
            string uid = this.Uid.Text.Trim();
            if (string.IsNullOrEmpty(uid))
            {
                PromptHelper.Prompt("未加载任何用户信息！");
            }
            else
            {
                QDDevPlat_V4 db = new QDDevPlat_V4();
                ftMod = db.Sys_Manager.FirstOrDefault(p => p.Uid == uid);

                if (ftMod == null)
                {
                    PromptHelper.Prompt("用户 [" + uid + "] 未保存或已经被删除！");
                }
            }

            return ftMod;
        }

        private void 复制单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopyFirstSelectedCellValue();
        }

        private void 复制所有选中单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopySelectedCellsValue();
        }

        /// <summary>
        /// 全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAll_Click(object sender, EventArgs e)
        {
            _strState = "";
            GridList_DataBind();
        }
        /// <summary>
        /// 允许登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllow_Click(object sender, EventArgs e)
        {
            _strState = "0";
            GridList_DataBind();
        }
        /// <summary>
        /// 禁止登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForbid_Click(object sender, EventArgs e)
        {
            _strState = "1";
            GridList_DataBind();
        }

    }
}
